import 'dart:io';

import 'package:valovault_reminder/common/config/val_assets_name.dart';
import 'package:valovault_reminder/common/config/val_define_const_data.dart';
import 'package:valovault_reminder/common/util/val_app_state_tool.dart';
import 'package:valovault_reminder/common/util/val_shared_preferences_tool.dart';
import 'package:valovault_reminder/pages/base/val_base_ui_page.dart';
import 'package:valovault_reminder/pages/home/components/val_switch_button_menu.dart';
import 'package:valovault_reminder/pages/home/models/val_post_record_model.dart';
import 'package:valovault_reminder/pages/home/views/val_publish_content_image_picker.dart';
import 'package:valovault_reminder/util/val_toast_kit.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';

import '../../common/ui/val_ui_kit_dialog_impl.dart';
import '../../util/val_eventbus_manager.dart';
import 'components/val_publish_input_alert_view.dart';

class ValPublishCarContentPage extends StatefulWidget {
  const ValPublishCarContentPage({super.key});

  @override
  State<ValPublishCarContentPage> createState() => _ValPublishCarContentPageState();
}

class _ValPublishCarContentPageState extends ValBaseUIPageState<ValPublishCarContentPage> {
  final FocusNode titleFieldNode = FocusNode();
  final FocusNode timeFieldNode = FocusNode();
  final FocusNode contentFieldNode = FocusNode();
  RxInt inputLength = 0.obs;
  List<AssetEntity> _imageFiles = [];
  final TextEditingController titleController = TextEditingController();
  final TextEditingController timeController = TextEditingController();
  final TextEditingController contentController = TextEditingController();
  bool selectedMenu = true;
  bool showErrorTip = false;
  final _scaffoldImagePickerKey = GlobalKey<ValPublishContentImagePickerState>();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    isAppBar = true;
    extendBodyBehindAppBar = true;
  }

  @override
  PreferredSizeWidget? get appBar {
    return darkAppBar(title: 'Edit');
  }

  void publishAccidentContentPost() async {
    if(_imageFiles.isEmpty || titleController.text.isEmpty
        || timeController.text.isEmpty || contentController.text.isEmpty) {
      // ValToastKit.showMessage('Images and selected labels are required！');
      _showCompleteTipView();
      setState(() {
        showErrorTip = true;
      });
      return;
    }
    AssetEntity assetEntity = _imageFiles.first;
    File? imageFile = await assetEntity.file;
    // String localFile = await saveFile(imageFile);
    String? filePath = imageFile?.path.split('tmp').last;
    DateTime now = DateTime.now();
    int timestamp = now.millisecondsSinceEpoch;
    String userId = await ValLocalStore.getValue(ValDefineConstData.valUserId, '99');
    ValPostRecordModel postModel = ValPostRecordModel(
      title: titleController.text,
      content: contentController.text,
      publishDate: timeController.text,
      image: filePath ?? '',//imageFile?.path ?? '',
      coverImage: filePath ?? '',//imageFile?.path ?? '',
      id: timestamp,
      userId: userId,
      accountId: userId,
      accountName: ValAppStateTool().accountInfo?.nickname ?? 'Jack',
      accountImage: ValAppStateTool().accountInfo?.avatarUrl ?? 'Jack',
      category: selectedMenu ? '2' : '1',
    );
    postModel.saveToDb();

    // Navigator.of(context).pop();
    ValToastKit.showMessage('Recording Success');
    ValEventbusManager.getInstance().eventBus.fire('postContent');
    setState(() {
      titleController.text = '';
      contentController.text = '';
      timeController.text = '';
      _imageFiles = [];
      _scaffoldImagePickerKey.currentState?.deleteAllImage();
      showErrorTip = false;
    });
  }

  Future<String> saveFile(File? selectFile) async {
    if (selectFile == null) {
      return "";
    }
    DateTime now = DateTime.now();
    int timestamp = now.millisecondsSinceEpoch;
    final dir = await getApplicationDocumentsDirectory();
    final temp = await getApplicationSupportDirectory();
    Directory tmpDir = Directory.systemTemp;
    // tmpDir.path;
    String filepath = "${dir.path}/post/${timestamp}_post_image.jpg";
    final file = File(filepath);
    final contents = await selectFile!.readAsString();
    file.writeAsString(contents, mode: FileMode.write);
    return filepath;
  }

  void _showCompleteTipView() {
    ValUIKitDialogImpl.showCenter(ValPublishInputAlertView(() {

    }));
  }

  Widget createInputView(String title,
      TextEditingController inputController,
      FocusNode contentNode,
      {double topOffset = 20, double height = 45, int maxLength = 200, bool emptyTip = false}
  ) {
    return Container(
      margin: EdgeInsets.only(left: 19, right: 19, top: topOffset),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: const EdgeInsets.only(left: 6, right: 6, bottom: 6),
            child: Text(title,
              style: TextStyle(color: (emptyTip ? const Color(0xFFFF0004) : const Color(0xFFFAC43F)), fontSize: 20, fontWeight: FontWeight.w500),),
          ),
          Container(
            height: height,
            alignment: Alignment.centerLeft,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(15),
            ),
            child: TextField(
              controller: inputController,
              style: const TextStyle(fontSize: 20),
              focusNode: contentNode,
              maxLength: maxLength,
              onTapOutside: (e) {
                contentNode.unfocus();
              },
              decoration: const InputDecoration(
                counterText: '', //自带计算长度提示
                hintText: '',
                hintStyle: TextStyle(fontSize: 20, color: Color.fromRGBO(0, 0, 0, 0.5)),
                isDense: true,
                contentPadding: EdgeInsets.only(left: 16, top: 18, right: 10),
                border: OutlineInputBorder(
                  gapPadding: 0,
                  borderSide: BorderSide(
                    width: 0,
                    style: BorderStyle.none,
                  ),
                ),
              ),
            ),
            // const Text('Enter your title：', style: TextStyle(color: Color.fromRGBO(0, 0, 0, 0.5), fontSize: 20,),),
          ),
        ],
      ),
    );
  }

  Widget createAccidentContentView({bool emptyTip = false}) {
    return Container(
      margin: const EdgeInsets.only(left: 19, right: 19, top: 16),
      height: 147,

      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: const EdgeInsets.only(left: 6, right: 6, bottom: 6),
            child: Text('Content',
              style: TextStyle(color: emptyTip ? const Color(0xFFFF0004) : const Color(0xFFFAC43F), fontSize: 20, fontWeight: FontWeight.w500),),
          ),
          Expanded(
            child: Container(
              padding: const EdgeInsets.all(8),
              decoration: const BoxDecoration(
                color: Color(0xFFF8F8F8),
                borderRadius: BorderRadius.all(Radius.circular(12)),
              ),
              child: Column(
                children: [
                  Expanded(
                    child: TextField(
                      controller: contentController,
                      style: const TextStyle(fontSize: 20),
                      focusNode: contentFieldNode,
                      textInputAction: TextInputAction.send,
                      keyboardType: TextInputType.multiline,
                      minLines: 1,
                      maxLines: 100,
                      maxLength: 200,
                      onTapOutside: (e) {
                        contentFieldNode.unfocus();
                      },
                      onChanged: (value) {
                        // setState(() {
                        inputLength = value.length.obs;
                        // });
                      },
                      decoration: const InputDecoration(
                        counterText: '', //超长提示
                        hintText: '',
                        hintStyle: TextStyle(fontSize: 12, color: Color.fromRGBO(0, 0, 0, 0.5)),
                        isDense: true,
                        contentPadding: EdgeInsets.only(left: 16, top: 18, right: 10),
                        border: OutlineInputBorder(
                          gapPadding: 0,
                          borderSide: BorderSide(
                            width: 0,
                            style: BorderStyle.none,
                          ),
                        ),
                      ),
                    ),
                  ),
                  // Container(
                  //   height: 20,
                  //   padding: const EdgeInsets.only(right: 6),
                  //   alignment: Alignment.centerRight,
                  //   child: Obx(() => Text('$inputLength/200',
                  //     style: const TextStyle(color: Color.fromRGBO(0, 0, 0, 0.3), fontSize: 10),)
                  //   ),
                  // ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget createSelectImagesView() {
    return Container(
      height: 136,
      margin: const EdgeInsets.only(left: 24, right: 24, top: 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: const EdgeInsets.only(left: 6, right: 6, bottom: 6),
            child: const Text('Photo',
              style: TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.w500),),
          ),

          Expanded(
            child: Container(
              height: 106,
              decoration: BoxDecoration(
                color: const Color.fromRGBO(69, 69, 69, 1),
                borderRadius: BorderRadius.circular(20),
                image: const DecorationImage(
                    image: AssetImage('${ValAssetsName.ASSETS_Message}val_publish_image_ground.png'),
                    fit: BoxFit.fill),
              ),
              child: ValPublishContentImagePicker(key: _scaffoldImagePickerKey, imageCount: 3, finishSelected: (List<AssetEntity> imageFiles) {
                _imageFiles = imageFiles;
              },),
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget buildBody(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFF303030),
      body: SafeArea(
        child: SingleChildScrollView(
          child: Column(
            children: [
              //输入内容
              Container(height: 381,
                margin: const EdgeInsets.only(left: 24, right: 24, top: 10),
                decoration: BoxDecoration(
                  color: const Color.fromRGBO(69, 69, 69, 1),
                  borderRadius: BorderRadius.circular(20),
                  image: const DecorationImage(
                      image: AssetImage('${ValAssetsName.ASSETS_Message}val_publish_input_ground.png'),
                      fit: BoxFit.fill),
                  // border: Border.all(
                  //     width: 1, style: BorderStyle.solid, color: const Color(0xFFE8A229))
                ),
                child: Column(
                  children: [
                    createInputView('Name', titleController, titleFieldNode, maxLength: 20, emptyTip: showErrorTip && titleController.text.isEmpty),
                    createInputView('Time', timeController, timeFieldNode, topOffset: 16, emptyTip: showErrorTip && timeController.text.isEmpty),
                    createAccidentContentView(emptyTip: showErrorTip && contentController.text.isEmpty),
                  ],
                ),
              ),
              //选图
              createSelectImagesView(),
              const Padding(padding: EdgeInsets.only(top: 30)),
              Container(
                height: 33,
                width: 220,
                child: ValSwitchButtonMenu(
                  onString: "Accident",
                  offString: "Maintenance",
                  fontSize: 12,
                  fontWeight: FontWeight.w400,
                  pressed: selectedMenu, onTap: (index){
                    setState(() {
                      selectedMenu = index == 0 ? true : false;
                    });
                }),
              ),
              const Padding(padding: EdgeInsets.only(top: 30)),
              //发送按钮
              GestureDetector(
                onTap: publishAccidentContentPost,
                child: Container(
                  margin: const EdgeInsets.only(left: 44, right: 44, bottom: 40),
                  height: 41,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    gradient: const LinearGradient(
                      begin: Alignment.centerLeft,
                      end: Alignment.centerRight,
                      colors: [
                        Color(0xFFE5FF48),
                        Color(0xFF7BCD4A),
                      ],
                    ),
                    borderRadius: BorderRadius.circular(5),
                  ),
                  child: const Text("Publish",
                    style: TextStyle(color: Color(0xFF333333), fontSize: 20, fontWeight: FontWeight.w500),),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
